package com.zdsoft.site.mina.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务器端业务逻辑
 */
public class TimeServerHandler extends IoHandlerAdapter {

	// 定义监听端口
    private static final int PORT = 8015;
    private static Logger logger=LoggerFactory.getLogger(TimeServerHandler.class);
    /**
     * 连接创建事件
     */
    @Override
    public void sessionCreated(IoSession session){
        // 显示客户端的ip和端口
    	logger.debug("sessionCreated: remoteAddr={}",session.getRemoteAddress().toString());
    }
    
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.debug("sessionOpened");
	}
	
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
        logger.debug("exceptionCaught");
    }
    /**
     * 消息接收事件
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        String strMsg = message.toString();
        logger.debug("接收到客户端来的消息:{}",strMsg);

        if (strMsg.trim().equalsIgnoreCase("quit")) {
            session.close(true);
            return;
        }
        // 返回消息字符串
        session.write("Hi Client!");
        //session.close(false);
        // 打印客户端传来的消息内容
        
    }
	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.debug("messageSent 发送消息到客户端:{}",message);
	}
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    	logger.debug("IDLE",session.getIdleCount(status));
    }

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.debug("sessionClosed");
	}
	
	@Override
	public void inputClosed(IoSession session) throws Exception {
		//super.inputClosed(session);
		session.close(false);
		logger.debug("inputClosed server");
	}
	
	public static void main(String[] args) throws IOException {
        // 创建服务端监控线程
        IoAcceptor acceptor = new NioSocketAcceptor();
        //IoAcceptor acceptor =new NioDatagramAcceptor();
        //设置读取数据的缓冲区大小
        acceptor.getSessionConfig().setReadBufferSize(2048);
        //读写通道10秒内无操作进入空闲状态
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        // 设置日志记录器
        //acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        // 设置编码过滤器
        acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        // 指定业务逻辑处理器
        acceptor.setHandler(new TimeServerHandler());
        // 绑定端口
        acceptor.bind(new InetSocketAddress(PORT));
        logger.debug("服务器侦听启动,端口[{}]",PORT);
    }
    
}
